package cn.xuqiudong.rpc.serializer.hessian;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import cn.xuqiudong.rpc.cluster.exception.XqdCommonException;
import cn.xuqiudong.rpc.serializer.XqdSerializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 描述: 基于Hessian2的的序列化方式
 * @author Vic.xu
 * @date 2022-02-21 11:08
 */
public class Hessian2Serializer implements XqdSerializer {
    @Override
    public <T> byte[] serialize(T obj) {
        HessianOutput hessianOutput = null;
        ////try with  resource
        try(ByteArrayOutputStream os = new ByteArrayOutputStream()){
            hessianOutput = new HessianOutput(os);
            hessianOutput.writeObject(obj);
            return os.toByteArray();
        }catch(Exception e){
            throw new XqdCommonException("Hessian2 序列化失败", e);
        }finally {
            if(hessianOutput!=null){
                try {
                    hessianOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {

        HessianInput hessianInput = null;

        //try with  resource
        try(ByteArrayInputStream is = new ByteArrayInputStream(data)){
            hessianInput = new HessianInput(is);
            return (T) hessianInput.readObject();
        }catch(Exception e){
            throw new XqdCommonException("Hessian2 反序列化失败", e);
        }finally {
            if(hessianInput!=null){
                hessianInput.close();
            }
        }
    }

    @Override
    public boolean selfDescribed() {
        return true;
    }
}
